<?php
function game_go(&$arrReturn)
{
    global $db;
    $speNo = intval($_GET['no']);
    $isToAuto = true;
    
    if(date( "H" ) < 9) 
    {
    	//取下期时间
    	$sql = "SELECT id,kgtime FROM gamepk10 WHERE kj = 0 AND kgtime > NOW() order by id limit 1";
        $query = $db->query($sql);
        if($rs = $db->fetch_array( $query ))
        {
             $arrRet['nextid'] = $rs['id'];
             $arrRet['nexttime'] = $rs['kgtime'];
        }
        else
        {
			 $sql = "select DATE_ADD(NOW(),INTERVAL 60 SECOND) nowtime";
        	 $query = $db->query($sql);
        	 $rs = $db->fetch_array( $query );
			 $arrRet['nextid'] ='0';
             $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
        }
    	$arrReturn['msg'] = 'not in open result time(pk)';
    	return;
	}
    
    $No = intval($speNo);
    if($speNo == 0)
    {
		$sql = "select gameno from game_result where gametype='gamepk' and isopen = 0 order by gameno desc limit 1 ";
    	$query = $db->query($sql);
    	if($rs = $db->fetch_array( $query ))
    	{
    		$No = $rs["gameno"];
		}
    	else
    	{ 
    		//保证采集不到但下盘时间快到时自动下注
		    $sql = "SELECT id,kgtime,now() as nowtime FROM gamepk10 WHERE kj = 0 AND zdtz_r = 0 AND kgtime > NOW() ORDER BY kgtime LIMIT 1";
		    $query = $db->query($sql);
		    if($rs = $db->fetch_array( $query ))
		    {
		        $NextNo = $rs['id'];
		        if(strtotime($rs['kgtime']) - strtotime($rs['nowtime']) < 30)
		        {
			        //自动投注
			        AutoPress($arrReturn,$No-1,$NextNo);
				}
		    }
    		$arrReturn['code'] = "ok";
    		$arrReturn['msg'] = "no open game record(pk)";
    		$arrReturn['log'] .= LogFormat("no open game record(pk)");
    		return;
		}
    }
    else
    {
    	$isToAuto = false;
		$sql = "SELECT id FROM gamepk10 WHERE kj = 0 and id = '{$No}' ";
    	$query = $db->query($sql);
    	if($rs = $db->fetch_array( $query ))
    	{
    		$No = $rs["id"];
		}
    	else
    	{
    		$arrReturn['code'] = "ok";
    		$arrReturn['msg'] = "{$No} had opened(pk)";
    		$arrReturn['log'] .= LogFormat("{$No} had opened(pk)");
    		return;
		}
    } 
    
    $arrReturn['no'] = $No;
    $strkjNum = GetGameResult($No);
    
    $kjnum_array = explode( "|", $strkjNum );
	if ( count($kjnum_array) == 10 ) //取到了
	{
		//更新开奖状态
	    $sql = "update game_result set isopen = 1,opentime = now() where gametype = 'gamepk' and gameno = '{$No}'";
	    $db->query($sql);
	    
		$arrReturn['log'] .= LogFormat("open result string:" . $strkjNum . " (pk)");
		$arrReturn['log'] .= LogFormat('begin open time:' . date('Y-m-d H:i:s') . " (pk)");
	    //开奖pk10
	    $zj_a =  substr($No,-1); //期号尾数;
	    $index = $zj_a - 1;
	    if($zj_a == 0) $index = 9;
	    $zj_b =  $kjnum_array[$index];//第n个数字
	    $zj_c =  -1;
	    $zj_result = $zj_b;
	    $sql = "call web_kj_gamepk10({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
		$arr = $db->Mysqli_Multi_Query($sql);
		$arrRet['code'] = $arr[0][0]["result"];
		$arrRet['msg'] = $arr[0][0]["msg"];
		$strlog = "pk10 " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})".  " (pk)";
		$arrReturn['log'] .= LogFormat($strlog);
		//开奖gj10
	    $zj_a = $kjnum_array[0];
	    $zj_b = $kjnum_array[1];
	    $zj_c = -1;
	    $zj_result = $zj_a;
	    $sql = "call web_kj_gamegj10({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')"; 
		$arr = $db->Mysqli_Multi_Query($sql);
		$arrRet['code'] = $arr[0][0]["result"];
		$arrRet['msg'] = $arr[0][0]["msg"];
		$strlog = "gj10 " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})".  " (pk)";
		$arrReturn['log'] .= LogFormat($strlog);
		//开奖pk22
	    $zj_a = $kjnum_array[0];
	    $zj_b = $kjnum_array[1];
	    $zj_c = $kjnum_array[2];
	    $zj_result = $zj_a + $zj_b + $zj_c;
	    $sql = "call web_kj_gamepk22({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')"; 
		$arr = $db->Mysqli_Multi_Query($sql);
		$arrRet['code'] = $arr[0][0]["result"];
		$arrRet['msg'] = $arr[0][0]["msg"];
		$strlog = "gj10 " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})".  " (pk)";
		$arrReturn['log'] .= LogFormat($strlog);
		//开奖pk龙虎
	    $zj_a = $kjnum_array[0];
	    $zj_b = $kjnum_array[9];
	    $zj_c = -1;
	    $zj_result = (($kjnum_array[0] > $kjnum_array[9])?1:2);
	    $sql = "call web_kj_gamepklh({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
		$arr = $db->Mysqli_Multi_Query($sql);
		$arrRet['code'] = $arr[0][0]["result"];
		$arrRet['msg'] = $arr[0][0]["msg"];
		$strlog = "pklh " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})".  " (pk)";
		$arrReturn['log'] .= LogFormat($strlog);
		//开奖pk冠亚军
	    $zj_a = $kjnum_array[0];
	    $zj_b = $kjnum_array[1];
	    $zj_c = -1;
	    $zj_result = $zj_a + $zj_b;
	    $sql = "call web_kj_gamepkgyj({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')"; 
		$arr = $db->Mysqli_Multi_Query($sql);
		$arrRet['code'] = $arr[0][0]["result"];
		$arrRet['msg'] = $arr[0][0]["msg"];
		$strlog = "pkgyj " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})".  " (pk)";
		$arrReturn['log'] .= LogFormat($strlog); 
		$arrReturn['log'] .= LogFormat('end open time:' . date('Y-m-d H:i:s') . " (pk)");
	}
	else //取不到结果
	{
		$arrReturn['code'] = 'noreward';
		$arrReturn['msg'] = "no open {$No} game result";
		$arrReturn['log'] = LogFormat("no open {$No} result!(pk)");
		return;
	}
	if($isToAuto)
	{
	    //给最新一盘自动投注
	    $NextNo = $No + 1;
	    $randScond = rand(3,5);
	    $sql = "SELECT id,DATE_ADD(NOW(),INTERVAL {$randScond} SECOND) nowtime FROM gamepk10 WHERE kj = 0 and id={$NextNo} limit 1";
	    $query = $db->query($sql);
	    if($rs = $db->fetch_array( $query ))
	    {
	        $arrRet['nextid'] = $rs['id'];
	        $arrRet['nexttime'] = $rs['nowtime'];
	        //自动投注
	        AutoPress($arrReturn,$No,$NextNo);
	    }
	} 
	
}
function AutoPress(&$arrReturn,$No,$NextNo)
{
	global $db;
	//pk10自动投注
	$sql = "call web_tz_gamepk10_auto_new({$No},{$NextNo})";
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "pk10 " . $arrRet['nextid'] . " auto press(" .$arrT[0][0]["result"] . ")" . " (pk)";
	$arrReturn['log'] .= LogFormat($strlog);
	//pk冠军自动投注
	$sql = "call web_tz_gamegj10_auto_new({$No},{$NextNo})";
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "pkgj " . $arrRet['nextid'] . " auto press(" .$arrT[0][0]["result"] . ")" . " (pk)";
	$arrReturn['log'] .= LogFormat($strlog);
	//pk22自动投注
	$sql = "call web_tz_gamepk22_auto_new({$No},{$NextNo})";
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "pk22 " . $arrRet['nextid'] . " auto press(" .$arrT[0][0]["result"] . ")" . " (pk)";
	$arrReturn['log'] .= LogFormat($strlog);
	//pklh自动投注
	$sql = "call web_tz_gamepklh_auto_new({$No},{$NextNo})";
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "pk22 " . $arrRet['nextid'] . " auto press(" .$arrT[0][0]["result"] . ")" . " (pk)";
	$arrReturn['log'] .= LogFormat($strlog);
	//pkgyj自动投注
	$sql = "call web_tz_gamepkgyj_auto_new({$No},{$NextNo})";
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "pk22 " . $arrRet['nextid'] . " auto press(" .$arrT[0][0]["result"] . ")" . " (pk)";
	$arrReturn['log'] .= LogFormat($strlog);
	$arrReturn['log'] .= LogFormat('end autopress time:' . date('Y-m-d H:i:s') ." (pk)");
}
function GetGameResult($theNo)
{ 
	global $db;
    $ret = "";
    
    $sql = "select gameresult from game_result where gametype='gamepk' and gameno = '{$theNo}' and isopen = 0"; 
    $query = $db->query($sql);
    if($rs = $db->fetch_array( $query ))
    {
    	$ret = $rs["gameresult"];
	}
	
	return $ret;
}


error_reporting( 0 );
set_time_limit( 200 );
include_once( "inc/conn.php" );
include_once( "inc/function.php" );
if ( $_GET['key'] == "kj_pktype_result" )
{
     $arrRet = array('code'=>'ok', //
    				'no' =>'',
                    'msg'=>'', //错误信息 -1:不在开奖时间内，0：开奖成功，1：该期已开过奖，2：取中奖赔率错误，99：系统错误
                    'log'=>'',
                    'nextid'=>'', //下一盘id
                    'nexttime'=>'' //下一篇开奖时间
        );
    game_go($arrRet);
    
    if ($arrRet['nextid'] == '')
    {
    	$RandSecond = rand(3,5);
		$sql = "select date_add(NOW(),INTERVAL {$RandSecond} SECOND) nowtime,id from gamepk10 where kgtime > now() and kj = 0 order by id limit 1";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrRet['nextid'] = $rs['id'];
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
		}
		else
		{
			$arrRet['nextid'] ='0';
            $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
		}
        
    }
    //返回
    echo json_encode($arrRet);
}
$db->close( );